<template>
  <div class="app-container">
    <!-- <div class="block" style="width:100% !important"> -->
      <div class="query-wrapper" model="queryParams" style="margin-bottom: 20px;"> 
            <el-select
              v-model="queryParams.vesselName"
              filterable
              clearable
              placeholder="Vessel"
              style="width:180px"
              @change="selectVessel(queryParams)"
            >
              <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
              </el-option>
            </el-select> 
            &nbsp;&nbsp;
            <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage" style="width:90px">
              <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
              </el-option>
            </el-select> 
            &nbsp;&nbsp; 
              <el-select v-model="queryParams.supplier" filterable clearable placeholder="Supplier">
              <el-option :key="item.fullName" :label="item.fullName" :value="item.fullName" v-for="item in suppliers">
              </el-option>
            </el-select> 
            &nbsp;&nbsp;            
            <el-button type="primary"  v-hasPermi="['bunkerSupplyRecord:search']"  icon="search" @click="search">{{
              $t("ship.button.search")
            }}</el-button>
             <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
            <span>&nbsp;&nbsp;&nbsp;&nbsp;</span> 

          <!-- <el-button type="primary" plain icon="Plus" @click="addClickEvent"  v-hasPermi="['bunkerSupplyRecord:add']">
            {{ $t("ship.button.plus") }}
          </el-button> -->
          <el-button type="warning" plain v-if="listData.length > 0" icon="download" @click="exportClickEvent"  v-hasPermi="['bunkerSupplyRecord:export']" >
          {{ $t("ship.button.export") }}
        </el-button>
      </div> 
  </div>

  <el-table stripe  ref="tableRef" :data="listData"  show-overflow-tooltip :border="true"
     :header-cell-style ="{textAlign:'center'}"  @sort-change="handleSortChange">
    <!-- <el-table-column prop="item" label="Item" /> -->
    <el-table-column prop="vesselName" label="Vessel Name" width="140" sortable="custom" :sort-orders="['descending', 'ascending']" >
	    
	</el-table-column>
	
    <el-table-column prop="voyageNo" label="Voyage" width="100" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />
    <el-table-column prop="portName" label="Port / Place"  width="120" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />
    <!-- <el-table-column prop="clientType" label="Client Type" sortable /> -->
    <el-table-column prop="suppliedDate" label="Delivery Date" width="140" align="center"  sortable="custom" :sort-orders="['descending', 'ascending']" />
    <el-table-column  label="VLSFO" header-align="center" align="center"    >
      <el-table-column prop = "suppliedVlsfo" label="QTY(MT)" align="center"  />
      <el-table-column prop = "suppliedVlsfoPrice" label="Price(USD/MT)" align="center"  width="120"  />
    </el-table-column>
    <el-table-column prop="" label="LSMGO" header-align="center" align="center">
      <el-table-column prop = "suppliedLsmgo" label="QTY(MT)" align="center" />
      <el-table-column prop = "suppliedLsmgoPrice" label="Price(USD/MT)" align="center" width="120"  />
    </el-table-column>
    <el-table-column prop="" label="LNG" header-align="center" align="center">
      <el-table-column prop = "suppliedLng" label="QTY(MMBTU)" align="center" width="120" />
      <el-table-column prop = "suppliedLngPrice" label="Price(USD/MMBTU)" align="center" width="150" />
       <el-table-column prop = "suppliedLngMt" label="QTY(MT)" align="center" width="120"/>
    </el-table-column>
    <el-table-column prop="supplier" label="Supplier"  width="180" align="center" >
       <template #default="scope"> 
        <el-form-item  >
          <el-select v-model="scope.row.supplier"  @change="handleSupplier(scope.row)" v-hasPermi="['bunkerSupplyRecord:edit']"> 
             <el-option  v-for="item in suppliers" :key="item.fullName"  :label="item.fullName"  :value="item.fullName"/>
          </el-select> 
          </el-form-item>
       </template>   
    </el-table-column>
    <el-table-column prop="suppliedDateIssue" label="Date Issue"  width="120" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />  
     <el-table-column prop="dueDate" label="Due Date"  width="120" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />  
    <el-table-column prop="suppliedDatePaid" label="Date Paid"  width="120" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />  
    <el-table-column prop="suppliedBdn" label="BDN"  width="150">
      <template #default="scope">
          <div v-if="scope.row.suppliedBdn"
            v-for="(url, index) in scope.row.suppliedBdn.split('&&&')" :key="index"  class="download-wrapper">
            <!-- <span>{{ getFileName(url) }}</span> -->
            <el-link v-if="docTypeList.includes(url.split('.').pop())" href="javascript:void(0)" @click="convertUrlDownload(url)">{{ getFileName(url) }}</el-link>
            <img v-else class="final-img" :src="convertUrl(url)" @click="handleViewer({ imageList: [convertUrl(url)], currentIndex: 0 })" />
          </div>
    </template>
    </el-table-column>
    <el-table-column prop="suppliedInvoice" label="Invoice"  width="150">
      <template #default="scope">
          <div v-if="scope.row.suppliedInvoice"
            v-for="(url, index) in scope.row.suppliedInvoice.split('&&&')" :key="index"  class="download-wrapper">
            <el-link v-if="docTypeList.includes(url.split('.').pop())" href="javascript:void(0)" @click="convertUrlDownload(url)">{{ getFileName(url) }}</el-link>
            <img v-else class="final-img" :src="convertUrl(url)" @click="handleViewer({ imageList: [convertUrl(url)], currentIndex: 0 })" />

          </div>
    </template>
    </el-table-column>
     
    <el-table-column prop="suppliedBankSlip" label="Bank Slip"  width="150">
      <template #default="scope">
          <div v-if="scope.row.suppliedBankSlip"
            v-for="(url, index) in scope.row.suppliedBankSlip.split('&&&')" :key="index"  class="download-wrapper">
            <el-link v-if="docTypeList.includes(url.split('.').pop())" href="javascript:void(0)" @click="convertUrlDownload(url)">{{ getFileName(url) }}</el-link>
            <img v-else class="final-img" :src="convertUrl(url)" @click="handleViewer({ imageList: [convertUrl(url)], currentIndex: 0 })" />

          </div>
      </template>
    </el-table-column>
	   
   <!-- <el-table-column prop="inquiryFiles" label="Inquiry Files"  width="250">
      <template #default="scope">
          <div v-if="scope.row.inquiryFiles && scope.row.inquiryFiles.length > 2" 
            v-for="(url, index) in scope.row.inquiryFiles.split(',')" :key="index"  class="download-wrapper">
            <span @click="uploadRemove(url,scope.row,2,'inquiryFiles')" >X</span>
            <a class="el-icon-download" href="javascript:void(0)"    @click="convertUrlDownload(url)"> {{ getFileName2(url) }} </a>
           </div>
        </template>
	 </el-table-column> -->
    
   <!-- <el-table-column prop="fobas" label="FOBAS"  width="120"  >
	    <template #default="scope">
	      <div v-if="scope.row.fobas"  class="download-wrapper">
          <span  @click="uploadRemove(scope.row.fobas,scope.row,4)" >X</span>
          <a href="javascript:void(0)" @click="convertUrlDownload(scope.row.fobas)"> {{  getFileName2(scope.row.fobas) }}</a>
		    </div> 
      </template>
	 </el-table-column> -->
	
    <el-table-column prop="createBy" label="Created By" width="120" align="center" />
    <el-table-column prop="updateBy" label="Updated By" width="120" align="center" />
    <!-- <el-table-column label="Operation" width="120"  v-hasPermi="['bunkerSupplyRecord:edit']" fixed="right">
      <template #default="scope">
        <span class="btn-primary" @click="editClickEvent(scope.row)">{{
          $t("ship.button.edit")
        }}</span>&nbsp;&nbsp;
        <span class="btn-primary" :disabled="scope.row.status == 1" @click="removeClickEvent(scope.row.id)">{{
          $t("ship.button.remove")
        }}</span>  
      </template>
    </el-table-column> -->
  </el-table>

  <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
    @pagination="pageQuery" style="float: right" />

  <el-dialog :width="900" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible"  >
    <el-form :model="formParam" :rules="rules" ref="custForm" class="form-wrapper">
      <el-row :gutter="20">
    <!-- 第一行 -->
    <el-col :span="12">
      <el-form-item label="Vessel Name" label-width="140px" prop="vesselName" required>
        <el-select
          v-model="formParam.vesselName"
          filterable
          clearable
          placeholder="choose vessel"
          style="width: 100%"
          @change="selectVessel(formParam)">
          <el-option 
            v-for="item in vessels"
            :key="item.vesselName"
            :label="item.vesselName"
            :value="item.vesselName"/> 
        </el-select>
      </el-form-item>
    </el-col>

    <el-col :span="12">
      <el-form-item label="Voyage" label-width="120px" prop="voyageNo" required>
        <el-select 
          v-model="formParam.voyageNo" 
          filterable 
          clearable 
          placeholder="choose voyage"
          style="width: 100%">
          <el-option 
            v-for="item in voyages"
            :key="item.voyageNo"
            :label="item.voyageNo"
            :value="item.voyageNo"/>
        </el-select>
      </el-form-item>
    </el-col>
  </el-row>

  <!-- 第二行 -->
  <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="PORT/PLACE" label-width="140px" prop="portPlace">
        <el-input v-model="formParam.portPlace"/>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="Date" label-width="120px" prop="bunkerDate" required>
        <el-date-picker 
          v-model="formParam.bunkerDate"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="Select Date"
          style="width: 100%"/>
      </el-form-item>
    </el-col>
  </el-row>

  <!-- 第三行：VLSFO -->
  <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="VLSFO Qty(mt)" label-width="140px" prop="vlsfoQty" required>
        <el-input-number 
          v-model="formParam.vlsfoQty"
          :precision="3"
          style="width: 100%"/>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="VLSFO PRICE" label-width="120px" prop="vlsfoPrice" required>
        <el-input-number 
          v-model="formParam.vlsfoPrice"
          :precision="2"
          :min="0"
          style="width: 100%"/>
      </el-form-item>
    </el-col>
  </el-row>

  <!-- 第四行：LSMGO -->
  <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="LSMGO Qty(mt)" label-width="140px" prop="lsmgoQty" required>
        <el-input-number 
          v-model="formParam.lsmgoQty"
          :precision="3"
          :min="0"
          style="width: 100%"/>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="LSMGO PRICE" label-width="120px" prop="lsmgoPrice" required>
        <el-input-number 
          v-model="formParam.lsmgoPrice"
          :min="0"
          :precision="2"
          style="width: 100%"/>
      </el-form-item>
    </el-col>
  </el-row>

  <!-- 第五行：LNG -->
  <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="LNG Qty(mt)" label-width="140px" prop="lngQty">
        <el-input-number 
          v-model="formParam.lngQty"
          :precision="3"
          :min="0"
          style="width: 100%"/>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="LNG PRICE" label-width="120px" prop="lngPrice">
        <el-input-number 
          v-model="formParam.lngPrice"
          :precision="2"
          :min="0"
          style="width: 100%"/>
      </el-form-item>
    </el-col>
  </el-row>

  <!-- 第六行：供应商 -->
  <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="SUPPLIER" label-width="140px" prop="supplier" required>
        <el-select
          v-model="formParam.supplier"
          filterable
          clearable
          placeholder="Choose Supplier"
          style="width: 100%">
          <el-option 
            v-for="item in suppliers"
            :key="item.fullName"
            :label="item.fullName"
            :value="item.fullName"/>
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="PAYMENT DUE" label-width="120px" prop="paymentDue" required>
        <el-date-picker 
          v-model="formParam.paymentDue"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="Select Date"
          style="width: 100%"/>
      </el-form-item>
    </el-col>
  </el-row>

  <!-- 第七行：文件上传 -->
  <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="REMITTENCE DATE" label-width="140px" prop="remittanceDate">
        <el-date-picker 
          v-model="formParam.remittanceDate"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="Select Date"
          style="width: 100%"/>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="INVOICE" label-width="120px" prop="invoiceFile">
        <div style="display: flex; width: 100%;gap: 10px;align-items: center;">
          <el-button 
            :disabled="uploadingMap.invoiceFile" 
            onclick="this.nextSibling.click()">
            {{ $t("ship.button.upload") }}
          </el-button>
          <input 
            type="file" 
            hidden 
            @change="uploadFile($event, 'invoiceFile')" 
            accept=".pdf,.jpg,.png"/>
          <a  v-if="formParam.invoiceFile" href="javascript:void(0)" @click="downloadPDF(formParam.invoiceFile)">{{ getFileName(formParam.invoiceFile) }}</a>
          <a v-else-if="formParam.invoice" href="javascript:void(0)" @click="downloadPDF(formParam.invoice)" style="color:#555"> {{ getFileName(formParam.invoice) }} </a>
        </div>
      </el-form-item>
    </el-col>
  </el-row>
  <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="CONTRACT" label-width="140px" prop="contractFile"> 
        <div style="display: flex;width: 100%; gap: 10px;align-items: center;">
        <el-button :disabled="uploadingMap.contractFile" onclick="this.nextSibling.click()"> {{ $t("ship.button.upload") }}</el-button>
        <input type="file" id="upload-file" v-show="false" @change="$event => { uploadFile($event, 'contractFile') }" accept=".pdf,.jpg,.png" />
        <a v-if="formParam.contractFile" href="javascript:void(0)" @click="downloadPDF(formParam.contractFile)">{{ getFileName(formParam.contractFile) }}</a>
        <a v-else-if="formParam.contract" href="javascript:void(0)" @click="downloadPDF(formParam.contract)" style="color:#555"> {{ getFileName(formParam.contract) }} </a>
        </div>
      </el-form-item>
    </el-col>
	
    <el-col :span="12">
      <el-form-item label="INQUIRY FILES" label-width="120px" prop="contractFile"> 
        <div style="display: flex; width: 100%; gap: 10px;align-items: center;">
        <el-button :disabled="uploadingMap.inquiryFilesFile" onclick="this.nextSibling.click()"> {{ $t("ship.button.upload") }}</el-button>
        <input type="file" id="upload-file" v-show="false" @change="$event => { uploadFile($event, 'inquiryFilesFile') }" multiple  accept=".pdf,.jpg,.png" />
			<div style="display: block;">
			   <a v-if="formParam.inquiryFilesFile " href="javascript:void(0)" @click="downloadPDF(formParam.inquiryFilesFile)">{{ getFileName(formParam.inquiryFilesFile) }}</a>
			   <div v-else-if="formParam.inquiryFiles && formParam.inquiryFiles.length > 2"  v-for="(url, index) in formParam.inquiryFiles.split(',')" :key="index"  >
					<a href="javascript:void(0)" @click="downloadPDF(formParam.inquiryFiles)" style="color:#555"> {{ getFileName(url) }}</a><br/>
			  </div>
			</div>
			  
        </div>
      </el-form-item>
    </el-col>
  </el-row>
  <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="BDN" label-width="140px" prop="bdnFile"> 
        <div style="display: flex;width: 100%; gap: 10px;align-items: center;">
        <el-button :disabled="uploadingMap.bdnFile" onclick="this.nextSibling.click()"> {{ $t("ship.button.upload") }}</el-button>
        <input type="file" id="upload-file" v-show="false" @change="$event => { uploadFile($event, 'bdnFile') }" accept=".pdf,.jpg,.png" />
        <a v-if="formParam.bdnFile" href="javascript:void(0)" @click="downloadPDF(formParam.bdnFile)">{{ getFileName(formParam.bdnFile) }}</a>
        <a v-else-if="formParam.bdn" href="javascript:void(0)" @click="downloadPDF(formParam.bdn)" style="color:#555"> {{ getFileName(formParam.bdn) }} </a>
        </div>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="FOBAS" label-width="120px" prop="fobasFile"> 
        <div style="display: flex; width: 100%; gap: 10px;align-items: center;">
        <el-button :disabled="uploadingMap.fobasFile" onclick="this.nextSibling.click()"> {{ $t("ship.button.upload") }}</el-button>
        <input type="file" id="upload-file" v-show="false" @change="$event => { uploadFile($event, 'fobasFile') }" accept=".pdf,.jpg,.png" />
        <a v-if="formParam.fobasFile" href="javascript:void(0)" @click="downloadPDF(formParam.fobasFile)">{{ getFileName(formParam.fobasFile) }}</a>
        <a v-else-if="formParam.fobas" href="javascript:void(0)" @click="downloadPDF(formParam.fobas)" style="color:#555"> {{ getFileName(formParam.fobas) }} </a>
        </div>
      </el-form-item>
    </el-col>
  </el-row>
</el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
        }}</el-button>        
        <el-button type="primary" :disabled="isSubmiting" @click="submitForm">{{
          $t("ship.button.submit")
        }}</el-button>

      </span>
    </template>
  </el-dialog> 
  <el-image-viewer v-if="imageViewParams.viewerVisible" :url-list="imageViewParams.imageList" :initial-index="imageViewParams.currentIndex" @close="imageViewParams.viewerVisible = false" />

</template>
<script lang="ts" setup name="bunkerSupplyRecord">
import { ref, onMounted, reactive } from "vue";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import service from "@/utils/request";
import { useTableDrag } from '@/hooks/useHooks';
import { downloadFile } from "@/utils/downloadFile";
import type {  UploadUserFile } from "element-plus";
const { tableRef } = useTableDrag();
const uploadUrl='/shipping/client/upload'
import {  convertUrl } from "@/utils/tencentCos";

const router = useRouter();
let custForm = ref(null);
const addFormModal = ref();
const dialogTitle = ref("");
const docTypeList = ['pdf', 'xlsx', 'xls', 'docx', 'doc','txt']
const initForm = {
  id: null, 
  vesselName: null,
  voyageNo: null,
  portPlace: null,
  contact: null,
  mobile: null,
  bunkerDate:null,
  lngPrice: null,
  paymentDue: null,
  lngQty:null, 
  remittanceDate: null,
  vlsfoQty: null,
  vlsfoPrice: null,
  lsmgoPrice: null,
  lsmgoQty: null, 
  supplier:null,  
  contract:null,
  invoice:null,
  inquiryFiles:null,
  inquiry: null,
  bdn:null,
  fobas:null, 
  invoiceFile: null,
  contractFile: null,
  inquiryFilesFile: null,
  inquiryFileList: null,
  bdnFile: null,
  fobasFile: null
};

let formParam = reactive(Object.assign({}, initForm)); 
const total = ref(0);
const statuss = ['UnApprove', "Approve", "Reject"]
const mailValid = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("email can't be blank"));
  } else if (!/^(?:\w+\.?)*\w+@(?:\w+\.)*\w+$/.test(value)) {
    callback(new Error('The email format is illegal!'));
  } else {
    callback();
  }
}
const rules = ref({
  vesselName: [{ required: true, message: "Vessel Name is required" }],
  voyageNo: [{ required: true, message: "Voyage is required" }],
  bunkerDate : [{ required: true, message: "Date is required" }],
  vlsfoPrice:  [{ required: true, message: "VLSFO PRICE is required" }],
  vlsfoQty:  [{ required: true, message: "VLSFO Qty(mt) is required" }],
  lsmgoQty:  [{ required: true, message: "LSMGO Qty(mt) is required" }],
  lsmgoPrice:  [{ required: true, message: "LSMGO PRICE is required" }],
  paymentDue: [{ required: true, message: "PAYMENT DUE is required" }],
  supplier : [{ required: true, message: "SUPPLIER is required" }],
  email: [{ required: true, trigger: "blur", validator: mailValid }]
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  vesselName: null,
  voyageNo: null,
  supplier: null,
  orderByColumn: undefined,
  isAsc: undefined,
});

let vessels = reactive([] as any)
let suppliers = reactive([] as any)
let voyages = reactive([] as any)
const selectVessel =(form)=>{ 
  queryParams.voyageNo = null
  if(form.vesselName != null && form.vesselName != undefined){ 
    let item = vessels.find(n=>n.vesselName == form.vesselName) 
    if(item){ 
      voyages = item.schedules
    } 
  } 
}

const listData = ref([]);
const refreshTable = async () => {
  let result = await service.get("/shipping/bunkerSupplyRecord/getTable", { params: queryParams });
  listData.value = result.data;
  total.value = result.total;
};
const resetQuery = (data:any) => {
    Object.assign(queryParams, data)
    listData.value = []
    total.value = 0
    //refreshTable()
}
const dialogFormVisible = ref(false);
let isAdd = false;
const resetForm = () => {
  // @ts-ignore
  custForm.value && custForm.value.resetFields();
};
const editClickEvent = (row: any) => {
  Object.keys(initForm).forEach((k) => (formParam[k] = row[k])); 
  // if (formParam.inquiryFiles === null || !Array.isArray(formParam.inquiryFiles)) {
  //   formParam.inquiryFiles = []
  // }
  dialogFormVisible.value = true
  resetForm()
  dialogTitle.value = "Update Bunker Supply Record"
  isAdd = false
  //addFormModal.value.show(row);
};

const handleSupplier = (row :any)=>{
    ElMessageBox.confirm("Confirm to Update Supplier?", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    let params =reactive({id:row.id, supplier: row.supplier})
    await service.put(`shipping/bunkerSupplyRecord/update`,params);

    refreshTable();
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "Update successfully!",
      position: "bottom-right",
    });
  });
}

 

const removeClickEvent = (id) => {
  ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    await service.delete(`shipping/bunkerSupplyRecord/${id}`);

    refreshTable();
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "Delete successfully!",
      position: "bottom-right",
    });
  });
};
 


const loading = ref(false);
const photos = ref<UploadUserFile[]>([]);
const addClickEvent = () => {
  dialogFormVisible.value = true
  dialogTitle.value = "Add Bunker Supply Record"
  isAdd = true
  Object.assign(formParam, initForm);
};

const exportClickEvent= ()=>{
  downloadFile("/shipping/bunkerSupplyRecord/export", queryParams, "bunkerSupplyRecord.xlsx");
}


let isSubmiting = ref(false)
const submitForm = () => {
  // @ts-ignore
  custForm.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let formData = new FormData(); 
    
    for (const [k, n] of Object.entries(formParam)) {
      if (k === 'id' || k === 'invoiceFile' || k === 'contractFile' || k === 'bdnFile' || k === 'fobasFile' || k === 'inquiryFilesFile') { 
        // @ts-ignore
        n && formData.append(k, n)   
      }  else {
        // @ts-ignore
        n && formData.append(k, n)
      }
    }
    isSubmiting.value = true
    try {
      await service[isAdd ? "post" : "put"]("shipping/bunkerSupplyRecord", formData);
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "save successful!",
        position: "bottom-right",
      });
      dialogFormVisible.value = false;
      refreshTable();
    } catch (error) {
      console.log(error)
    } finally {
      isSubmiting.value = false
    }
  });
};

const pageQuery = async (e) => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const search = () => {
  refreshTable();
}; 

const convertUrlDownload =(url:string ) => {
  const  pdfUrl=encodeURI(convertUrl(url))
  if(['pdf','docx','doc','xls','xlsx','txt'].some((item) => url.includes(item))){
    window.open(router.resolve({ path: '/pdfView/index', query: { pdfUrl: pdfUrl} }).href, '_blank')
  }else{
    downloadPDF(url)
  }
}

const uploadRemove = (file,row,type) => {
  ElMessageBox.confirm("Confirm to Remove the file？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel"
  }).then(async () => {
    
	let params = {
	  id: row.id,
	  url: file,
	  type:type
	};
    await service.post("/shipping/bunkerSupplyRecord/deleteFile", params);
    refreshTable();
    ElNotification.success({
      title: "Prompt information",
      message: "delete the file success!",
      position: "bottom-right"
    });
  });
};

const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};
// 当前记录行图片预览
let imageViewParams = ref({
  viewerVisible: false,
  imageList: [],
  currentIndex: 0
})

const handleViewer = ({ imageList = [], currentIndex = 0 }) => {
  imageViewParams.value = { viewerVisible: true, imageList, currentIndex }
}
 // 获取文件名称
function getFileName(file: any) {
    if(!file){
      return '';
    }
    const name = file.name||file

    // 如果是url那么取最后的名字 如果不是直接返回
    if (name.lastIndexOf("/") > -1) {
      return name.slice(name.lastIndexOf("/") + 1);
    } else {
      return name;
    }
}

// 上传标志位
let uploadingMap = ref({})
const uploadFile = async (event: any, formKey: string) => {
  if (event.target == null || event.target.files[0] == null) {
    return;
  }
  if(formKey=="inquiryFilesFile"){
	  uploadingMap.value[formKey] = true
	  formParam[formKey] = event.target.files[0]   
  }else{
	  uploadingMap.value[formKey] = true
	  formParam[formKey] = event.target.files[0]   
  }

  // 文件上传操作后延迟1s可点击，避免太快操作
  setTimeout(() => {
    uploadingMap.value[formKey] = false
  }, 500)
};
 
function downloadPDF(url:String) { 
	  ElMessageBox.confirm("Confirm to Download the file？", "Download  Information", {
		type: "warning",
		confirmButtonText: "Confirm",
		cancelButtonText: "Cancel",
	  }).then(async () => {
      const newUrl = convertUrl(url);
			const a = document.createElement('a');
			a.href = newUrl;
			a.download = getFileName(newUrl);
			a.click();
	  });
	}
onMounted(async () => {
  service.get("/shipping/schedule/getAllSchedule").then(result=>{
    vessels = result.data
  })  
  let params = {supplierType: 'FUEL SUPPLIERS', status: 1}
  service.get("/shipping/supplier/list",{params:params}).then(result=>{
    suppliers = result.data
  })  
  refreshTable();
});
</script> 
<style lang="scss" scoped>
.download-wrapper{
  width: 100%;
  border-radius: 2px;
  padding:0 4px;
  overflow: hidden;
  font-size: 12px;
  >span{
    margin-right: 5px;
    color: #0674ce;
  }
  :deep(.el-link__inner){
    font-size: 12px;
  }
}
.final-img{
  width: 40px;
}
</style>